<?php

// 会员红包记录

namespace app\console\controller;

use think\Db;
use think\Url;
use think\Cache;
use think\Loader;
use think\Request;
use think\Controller;
use app\console\model\MemberPacket as MemberPacketModel;

class MemberPacket extends Controller
{

    /**
     * 会员红包记录列表
     * @param Request $request
     * @param MemberPacketModel $memberPacket
     * @return mixed
     */
    public function index(Request $request,MemberPacketModel $memberPacket)
    {
        // 获取参数
        $inquire = $request->instance()->param();

        // 搜索条件
        $condition['id'] = ['neq', '0'];
        if (!empty($inquire['title'])) $condition['title'] = ['like', '%' . $inquire['title'] . '%'];
        if (!empty($inquire['status'])) $condition['status'] = ['eq', $inquire['status']];

        // 读取红包记录
        $data = $memberPacket->with('Member')->where($condition)->paginate(10, false, ['query' => $inquire]);



        return $this->fetch('index', [
            'mate_title' => '红包记录列表',
            'data'       => $data
        ]);
    }

    /*
     * 红包记录删除
     */
    public function destroy($id)
    {

        if (MemberPacketModel::destroy($id)) {
            win('操作成功', Url::build('MemberPacket/index'));
        }

        fail('操作失败');

    }

    /*
     * 红包记录编辑
     */
    public function update($id)
    {

        if (Request::instance()->isPost()) {

            $data = Request::instance()->param();

            // 验证
            $validate = Loader::validate('MemberPacket');
            if (!$validate->scene('create')->check($data)) fail($validate->getError());

            // 提交数据
            $dispose = (new MemberPacketModel())->allowField(true)->save($data, ['id' => $id]);

            if ($dispose) {
                win('操作成功', Url::build('MemberPacket/index'));
            }

            fail('操作失败');

        }

        // 读取数据
        $item = Db::view('member_packet', 'id,member_id,title,price,actual_price,virtual_price,start_time,end_time,status,create_time')
            ->view('member', 'username,name', 'member_packet.member_id = member.id')
            ->where(['id' => $id])
            ->find();

        return $this->fetch('create', [
            "mate_title" => '红包记录查看',
            'item'       => $item

        ]);
    }

    /*
     * 排列顺序
     */
    public function sorting()
    {

        $id = Request::instance()->param('orderId/a');
        $sort = Request::instance()->param('sort/a');

        foreach ($id as $key => $value) {
            MemberPacketModel::where('id', $value)->update(['sort' => $sort[$key]]);
        }

        win('操作成功', Url::build('MemberPacket/index'));
    }

}
